﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Scorpicore.Data;
using Scorpicore.MVC.Models;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using System.Data.Entity.SqlServer;
using System.Globalization;
using System.Data.Entity.Core.Objects;
using Scorpicore.Models;

namespace Scorpicore.MVC.Controllers
{

    [ValidateInput(false)] 
    public class TopTenController : Controller
    {
        IUnitOfWork db;

        public TopTenController(IUnitOfWork db)
        {
            this.db = db;
        }

        public ActionResult RegisterBanknotes(int? denom)
        {
            //var result = db.Banknotes.All().OrderBy(b => b.Tracks.Count).Take(10);
            //var result = db.Banknotes.All().OrderBy(b => b.Tracks.Count).Take(10);

            return View(denom);
        }

        public ActionResult Cities()
        {
            return View();
        }

        public JsonResult ReadTopTenBanknotes([DataSourceRequest]DataSourceRequest request, int? denom, string userID)
        { 
            var banknotes = db.Banknotes.All().AsEnumerable();

            if (!string.IsNullOrEmpty(userID))
            {
                List<Banknote> banks = new List<Banknote>();

                foreach (var banknote in banknotes)
                {
                    foreach (var track in banknote.Tracks)
                    {
                        if (track.User.Id == userID)
                        {
                            banks.Add(banknote);
                            break;
                        }
                    }
                }

                banknotes = banks;
            }

            if (denom == null)
            {
                var result = banknotes
                    .OrderByDescending(b => b.Tracks.Count)
                    .Select(b => new TopTenBanknoteViewModel
                    {
                        Id = b.Id,
                        Distance = b.Distance,
                        Denomination = b.Denomination,
                        LastPlace = b.LastPlace,
                        Letters = b.Letters,
                        SerialNumber = b.SerialNumber,
                        ImageUrl = b.ImageUrl
                    }).Take(10);

               if (!string.IsNullOrEmpty(userID))
               {
                   
               }
                
               return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
            }
            else
            {
                Denomination den = Denomination.Two;
                switch (denom)
                {
                    case 5: den = Denomination.Five; break;
                    case 10: den = Denomination.Ten; break;
                    case 20: den = Denomination.Twenty; break;
                    case 50: den = Denomination.Fifty; break;
                    case 100: den = Denomination.Hundred; break;
                    default:
                        break;
                }

                var result = banknotes.Where(b => b.Denomination == den).AsEnumerable()
                   .OrderByDescending(b => b.Tracks.Count)
                   .Select(b => new TopTenBanknoteViewModel
                   {
                       Id = b.Id,
                       Distance = b.Distance,
                       Denomination = b.Denomination,
                       LastPlace = b.LastPlace,
                       Letters = b.Letters,
                       SerialNumber = b.SerialNumber,
                       ImageUrl = b.ImageUrl
                   }).Take(10);
               return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
            }

        }

        public JsonResult ReadTracks([DataSourceRequest]DataSourceRequest request, int Id)
        {
            var context = new DataContext();
            var result = context.Banknotes.Find(Id);
            //result = result.Where(b => b.Id == Id);
            var tracks = result.Tracks;
            var newTracks = tracks.Select(t => new TracksInTopTenBanknotesViewModel
                {
                    Id = t.Id,
                    Date = t.Date,
                    Place = t.Place.Name,
                    User = t.User.UserName,
                    Message = t.Message
                });

            return Json(newTracks.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

        public JsonResult ReadTracksByName([DataSourceRequest]DataSourceRequest request, int Id)
        {
            var context = new DataContext();
            var result = db.Places.GetById(Id).Tracks;

            //result = result.Where(b => b.Id == Id);
            var newTracks = result.Select(t => new TracksInTopTenBanknotesViewModel
            {
                Id = t.Id,
                Date = t.Date,
                Place = t.Place.Name,
                User = t.User.UserName,
                Message = t.Message
            });

            return Json(newTracks.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

        public ActionResult UserBanknotes()
        {
            return View();
        }
        public JsonResult ReadTopTenUsers([DataSourceRequest]DataSourceRequest request)
        {
            var context = new DataContext();
            var result = context.Users.Select(u => new TopTenUsersViewModel
                {
                    Id = u.Id,
                    AvatarUrl = u.AvatarUrl,
                    UserName = u.UserName,
                    Banknotes = u.Banknotes.Count,
                    Tracks = u.Tracks.Count
                }).AsEnumerable().OrderByDescending(b => b.Banknotes).Take(10);
            //result = result.Where(b => b.Id == Id);

            return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

        public JsonResult ReadPlaces([DataSourceRequest]DataSourceRequest request)
        {
            var places = (from p in db.Tracks.All()
                          group p by p.Place.Name into g
                          orderby g.Count() descending
                          select new PlacesFrequencyViewModel
                          {
                              Name = g.Key,
                              Count = g.Count()
                          }).ToList();

            var allPlaces = db.Places.All();

            foreach (var place in allPlaces)
            {
                foreach (var UniquePlace in places)
                {
                    if (place.Name == UniquePlace.Name)
                    {
                        UniquePlace.Id = place.Id;
                    }
                }
            }

            return Json(places.ToDataSourceResult(request),
                JsonRequestBehavior.AllowGet);
        }

        //public ActionResult DatesBanknotes()
        //{
        //    return View();
        //}
        public ActionResult DatesBanknotes()
        {
            var dateCounts =
                (from p in db.Tracks.All()
                 group p by EntityFunctions.TruncateTime((DateTime)p.Date) into g
                 orderby g.Count() descending
                 select new DateFrequencyViewModel
                {
                    Date = (DateTime)g.Key,
                    Count = g.Count()
                }).ToList();

            return View(dateCounts);
        }

        public ActionResult DateTracks(DateTime date)
        {
            var tracks = db.Tracks.All().Where(t => EntityFunctions.TruncateTime((DateTime)t.Date) == EntityFunctions.TruncateTime((DateTime)date)).
                    Select(TracksInTopTenBanknotesViewModel.FromTrack).ToList();

            return PartialView("_DateTracksPartial", tracks);
        }

        public ActionResult GetTracksByDate([DataSourceRequest]DataSourceRequest request, DateTime date)
        {
            var tracks = db.Tracks.All().Where(t => t.Date == date).
                    Select(TracksInTopTenBanknotesViewModel.FromTrack).ToList();

            return Json(tracks.ToDataSourceResult(request),
               JsonRequestBehavior.AllowGet);
        }

        public ActionResult Index()
        {
            return RedirectToAction("UserError", "Home");
        }
    }
}
